//
//  GetOrderViewController.m
//  Hui
//
//  Created by HawkingWang on 16/10/26.
//  Copyright © 2016年 Hui. All rights reserved.
//

#import "GetOrderViewController.h"
#import "UINavigationBar+BackgroundColor.h"//导航栏渐变
#import "GetOrderNavView.h"//导航栏View
#import "HADirect.h"//轮播
#import "MessageViewController.h"//消息Controller
#import "MineViewController.h"//我的Controller
#import "LoginWithPhoneViewController.h"//手机登录Controller
#import "GetOrderDetailViewController.h"//抢单详情Controller

#import "GetOrderHeaderView.h"//页眉
#import "GetOrderTableViewCell.h"//cell


#define BannerHeight (SCREEN_WIDTH / 375  * 170)
#define ButtonWidth (SCREEN_WIDTH / 4)

@interface GetOrderViewController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, HADirectActionDelegate>
@property (nonatomic, strong) HADirect *hadView;//轮播View
@end

@implementation GetOrderViewController
{
    GetOrderNavView *_navView;
    GetOrderHeaderView *_headerView;
    UIButton *_sliderButton;
    
    NSMutableArray *_tableViewArray;
    NSInteger count;
    NSMutableArray *_buttonArray;
    NSArray *_titleArray;
    
    CGFloat _alphaa;
    
    BOOL _didLoad;
    CGRect _headerFrame;
}

static NSString *const GetOrderTableViewCellID = @"GetOrderTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _tableViewArray = [NSMutableArray array];
    _buttonArray = [NSMutableArray array];
    _titleArray = @[@"外卖1", @"跑腿2", @"送货", @"大件", @"外卖2", @"跑腿2"];
    
    //设置导航栏
    [self setNav];
    
    count = 6;
    //设置ScrollView
    [self setScrollView];
    
    //设置页眉
    [self setHeaderView];
    
    [self.view bringSubviewToFront:_navView];
    
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.navigationController.navigationBar.hidden = YES;
    _didLoad = NO;
}


- (void)login{
    LoginWithPhoneViewController *login = [[LoginWithPhoneViewController alloc] init];
    login.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:login animated:YES];
}

- (void)alertShow:(NSString *)string{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"未登录" message:string preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        MineViewController *mine = [[MineViewController alloc] init];
        mine.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mine animated:YES];
    }];
    [alert addAction:cancle];
    UIAlertAction *login = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self login];
    }];
    [alert addAction:login];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark === 设置导航栏 ===
- (void)setNav{
    _navView = [[[NSBundle mainBundle] loadNibNamed:@"GetOrderNavView" owner:nil options:nil] lastObject];
    _navView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 64);
    _navView.backgroundColor = RGBACOLOR(53, 161, 238, 0);
    _navView.title.hidden = YES;
    [self.view addSubview:_navView];
    __weak __typeof__ (self)weakSelf = self;
    _navView.NavClick = ^(int num){
        switch (num) {
            case 0:
                [weakSelf jumpToMine];
                break;
            case 1:
                [weakSelf jumpToMessage];
                break;
            default:
                break;
        }
    };
}

- (void)jumpToMine{
    DLog(@"我的");
    [self alertShow:@"是否登录"];
    //    MineViewController *mine = [[MineViewController alloc] init];
    //    mine.hidesBottomBarWhenPushed = YES;
    //    [self.navigationController pushViewController:mine animated:YES];
}
- (void)jumpToMessage{
    DLog(@"消息");
    MessageViewController *message = [[MessageViewController alloc] init];
    message.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:message animated:YES];
}

#pragma mark === 设置ScrollView ===
- (void)setScrollView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * count, SCREEN_HEIGHT - 44);
    _scrollView.pagingEnabled = YES;//按页滚动
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.backgroundColor = RGBCOLOR(236, 236, 236);
    [self.view addSubview:_scrollView];
    
    for (int i = 0; i < count; i ++) {
        [_tableViewArray addObject:[self createTableViewAtIndex:i]];
    }
}


#pragma mark === 设置页眉 ===
- (void)setHeaderView{
    __weak __typeof__ (self) weakSelf = self;
    _headerView = [[[NSBundle mainBundle] loadNibNamed:@"GetOrderHeaderView" owner:nil options:nil] lastObject];
    _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, BannerHeight);
    [self.view addSubview:_headerView];
    
    //外卖 跑腿 送货 大件
    _headerView.scrollView.contentSize = CGSizeMake(ButtonWidth * count, 44);
    _headerView.scrollView.delegate = self;
    for (int i = 0; i < count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i * ButtonWidth, 0, ButtonWidth, 44);
        [button setTitle:_titleArray[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont fontWithName:APPFONT size:15];
        if (i == 0) {
            [button setTitleColor:APPCOLOR forState:UIControlStateNormal];
        }else{
            [button setTitleColor:APPBLACK forState:UIControlStateNormal];
        }
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.tag = 1000 + i;
        [button addTarget:self action:@selector(selectTitle:) forControlEvents:UIControlEventTouchUpInside];
        [_buttonArray addObject:button];
        [_headerView.scrollView addSubview:button];
    }
    
    
    //scrollView右滑按钮
    _sliderButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _sliderButton.frame = CGRectMake(SCREEN_WIDTH - (ButtonWidth / 3), BannerHeight, ButtonWidth / 3, 44);
    _sliderButton.backgroundColor = [UIColor clearColor];
    [_sliderButton addTarget:self action:@selector(sliderToRight) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:_sliderButton];
    
    
    _headerView.buttonClick = ^(int num){
        weakSelf.line.frame = CGRectMake(num * (SCREEN_WIDTH / 4), 43, SCREEN_WIDTH / 4, 1);
        weakSelf.scrollView.contentOffset = CGPointMake(num * SCREEN_WIDTH, 0);
    };
    
    //滑动条
    _line = [[UIView alloc] initWithFrame:CGRectMake(0, 43, SCREEN_WIDTH / 4, 1)];
    _line.backgroundColor = APPCOLOR;
    [_headerView.scrollView addSubview:_line];
    
    //设置轮播
    NSArray *arr = @[@"had1",@"had2",@"had3"];
    _hadView = [HADirect direcWithtFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH / 375 * 170) ImageArr:arr];
    [_headerView.bannerView addSubview:_hadView];
    _hadView.delegate = self;
    
    [_headerView setView];
    
}

- (void)selectTitle:(UIButton *)sender{
    NSInteger num = sender.tag - 1000;
    for (UIButton *button in _buttonArray) {
        [button setTitleColor:APPBLACK forState:UIControlStateNormal];
        if (button == sender) {
            [UIView animateWithDuration:0.2 animations:^{
                _line.frame = CGRectMake(num * ButtonWidth, 43, SCREEN_WIDTH / 4, 1);
            } completion:^(BOOL finished) {
                _scrollView.contentOffset = CGPointMake(num * SCREEN_WIDTH, 0);
                [button setTitleColor:APPCOLOR forState:UIControlStateNormal];
            }];
        }
    }
}
- (void)sliderToRight{
    CGFloat x = _headerView.scrollView.contentOffset.x + ButtonWidth;
    if ((ButtonWidth * count - (x + SCREEN_WIDTH) < ButtonWidth) || (x + SCREEN_WIDTH == ButtonWidth * count)) {
        x = ButtonWidth * count - SCREEN_WIDTH;
    }
    [_headerView.scrollView setContentOffset:CGPointMake(x , 0) animated:YES];
}


#pragma mark === 轮播Delegate ===
- (void)HADirectActionWithIndex:(NSInteger)index{
    NSLog(@"index = %ld", index);
}


#pragma mark === 创建tableView ===
- (UITableView *)createTableViewAtIndex:(NSInteger)index{
    UIView *HeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, BannerHeight + 44)];
    HeaderView.backgroundColor = [UIColor clearColor];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * index, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableHeaderView = HeaderView;
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 0.01f)];
    tableView.tag = 2000 + index;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = RGBCOLOR(236, 236, 236);
    //    tableView.bounces = NO;
    tableView.showsVerticalScrollIndicator = NO;
    [_scrollView addSubview:tableView];
    
    [tableView registerNib:[UINib nibWithNibName:@"GetOrderTableViewCell" bundle:nil] forCellReuseIdentifier:GetOrderTableViewCellID];
    return tableView;
}

#pragma mark === UITableViewDelegate ===
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return tableView.tag - 1999;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat height = SCREEN_HEIGHT - 64 - 44 - 49;
    CGFloat contentHeight = (tableView.tag - 1999) * 160;
    if (contentHeight < height) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        view.backgroundColor = [UIColor clearColor];
        return view;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height = SCREEN_HEIGHT - 44 - 49 - 64;
    CGFloat contentHeight = (tableView.tag - 1999) * 160;
    if (contentHeight < height) {
        return height - contentHeight;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 160;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger num = tableView.tag - 2000;
    
    GetOrderTableViewCell *cell = [_tableViewArray[num] dequeueReusableCellWithIdentifier:GetOrderTableViewCellID];
    if (indexPath.row > 0) {
        [cell setLoseEfficacyView];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //跳转时tableView不至顶
    _didLoad = YES;
    
    GetOrderDetailViewController *getOrder = [[GetOrderDetailViewController alloc] init];
    getOrder.state = 0;
    getOrder.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:getOrder animated:YES];
    
}


#pragma mark === 设置tableView的偏移量 ===
-(void)setTableViewContentOffsetWithTag:(NSInteger)tag contentOffset:(CGFloat)offset{
    CGFloat tableViewOffset;
    if(offset >= BannerHeight - 64){
        tableViewOffset = BannerHeight - 64;
    }else{
        tableViewOffset = offset;
    }
    for (UITableView *tableView in _tableViewArray) {
        if (tableView.tag != tag) {
            [tableView setContentOffset:CGPointMake(0, tableViewOffset) animated:NO];
        }
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (!_didLoad) {
        if ([scrollView isKindOfClass:[UITableView class]]) {
            //导航栏渐变
            CGFloat offset = scrollView.contentOffset.y;
            CGFloat alpha = offset / (BannerHeight - 64);
            _navView.backgroundColor = RGBACOLOR(53, 161, 238, alpha);
            if (scrollView.contentOffset.y >= (BannerHeight - 65)) {
                _navView.title.hidden = NO;
            }else{
                _navView.title.hidden = YES;
            }
            //滚动页位置
            if (scrollView.contentOffset.y >= BannerHeight - 64) {
                _headerView.frame = CGRectMake(0, - BannerHeight + 64, SCREEN_WIDTH, BannerHeight + 44);
            }else {
                _headerView.frame = CGRectMake(0, - scrollView.contentOffset.y, SCREEN_WIDTH, BannerHeight + 44);
            }
            return;
        }
    }
    
    //滑动条位置
    if (scrollView == _scrollView) {
        CGFloat x = scrollView.contentOffset.x;
        if (x < 0) {
            _line.frame = CGRectMake(0, 43, SCREEN_WIDTH / 4, 1);
        }else if (x > SCREEN_WIDTH * (count - 1)){
            _line.frame = CGRectMake(SCREEN_WIDTH / 4 * (count - 1), 43, SCREEN_WIDTH / 4, 1);
        }else{
            _line.frame = CGRectMake(x / 4, 43, SCREEN_WIDTH / 4, 1);
        }
        
        //当前ScrollView显示范围
        CGFloat sliderX = _line.frame.origin.x;
        //范围内显示了_slider
        if (_headerView.scrollView.contentOffset.x <= sliderX && (_headerView.scrollView.contentOffset.x + SCREEN_WIDTH) >= (sliderX + ButtonWidth)) {
            return;
        }
        //滑动条左侧显示
        else if (_headerView.scrollView.contentOffset.x > sliderX){
            _headerView.scrollView.contentOffset = CGPointMake(sliderX, 0);
        }
        //滑动条右侧显示
        else{
            _headerView.scrollView.contentOffset = CGPointMake(sliderX - 3 * ButtonWidth, 0);
        }
    }
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger num = _line.frame.origin.x / ButtonWidth;
    for (UIButton *button in _buttonArray) {
        [button setTitleColor:APPBLACK forState:UIControlStateNormal];
        if (button.tag - 1000 == num) {
            [button setTitleColor:APPCOLOR forState:UIControlStateNormal];
        }
    }
    //tableview联动
    if (scrollView.contentOffset.y >= 0 && [scrollView isKindOfClass:[UITableView class]]) {
        [self setTableViewContentOffsetWithTag:scrollView.tag contentOffset:scrollView.contentOffset.y];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //tableview联动
    if (scrollView.contentOffset.y >= 0 && [scrollView isKindOfClass:[UITableView class]]) {
        [self setTableViewContentOffsetWithTag:scrollView.tag contentOffset:scrollView.contentOffset.y];
    }
    
//    for (UITableView *tableview in _tableViewArray) {
//        DLog(@"%f %f /// %f %f", tableview.frame.size.width, tableview.frame.size.height, tableview.frame.origin.x, tableview.frame.origin.y);
//    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
